import utils from "@/utils/utils";
const state = {
  //存放的键值对就是所要管理的状态
  userinfo: "",
};

const mutations = {
  SET_USERINFO(state, userinfo) {
    state.userinfo = userinfo;
  },
};
const actions = {
  login({ commit }) {
    uni.login({
      provider: "weixin",
      success: (res) => {
        // TODO: 调用后端接口获取用户token 和 用户信息
        uni.$u.http.post("/v1.user/login", { code: res.code }).then((data) => {
          // 设置token
          utils.setToken(data.token);
        });
      },
      fail: (res) => {
        utils.showToast("获取授权信息失败");
      },
    });
  },
  authUserInfo({ commit }) {
    uni.getUserProfile({
      desc: "登录",
      lang: "zh_CN",
      success: async (res) => {
        if (res.errMsg.includes("ok")) {
          console.log(res);
          commit("SET_USERINFO", {
            nickname: res.userInfo.nickName,
            sex: res.userInfo.gender,
            avatar: res.userInfo.avatarUrl,
          });
          uni.showLoading({
            title: "正在授权",
          });
          setTimeout(() => {
            uni.hideLoading();
          }, 100);
        } else {
          utils.showToast("您取消了登录授权");
        }
      },
      fail: (res) => {
        console.log(res);
        utils.showToast("获取用户信息失败");
      },
    });
  },
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
